package com.tianheng.wanzhou.datacollecting.db.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * @Author: yujw
 * @Date: 2020/6/30 14:52
 * @Version 1.0
 */
@Component
public class DBMetaHandler implements MetaObjectHandler {
    private static final String C_TIME = "createTime";
    private static final String U_TIME = "updateTime";
    private static final String U_TIME1 = "tLastWriteTime";


    private void setData(MetaObject meta, String field, long value, boolean force){
        if( meta.hasSetter(field) ){
            Object data = getFieldValByName(field, meta);
            if( force ||data == null || (long)data < 1 )
                setFieldValByName(field, value, meta);
        }
    }

    private void setData(MetaObject meta, String field, String value, boolean force){
        if( meta.hasSetter(field) ){
            Object data = getFieldValByName(field, meta);
            if( force ||data == null )
                setFieldValByName(field, value, meta);
        }
    }

    private void setData(MetaObject meta, String field, int value, boolean force){
        if( meta.hasSetter(field) ){
            Object data = getFieldValByName(field, meta);
            if( force || data == null || (int)data < 1 )
                setFieldValByName(field, value, meta);
        }
    }

    @Override
    public void insertFill(MetaObject meta) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        this.setData(meta, C_TIME, df.format(new Date()), true);
        this.setData(meta, U_TIME, df.format(new Date()), true);
        this.setData(meta, U_TIME1, df.format(new Date()), true);


//        long id = getUserId();
//        if( id > 0 ){
//            this.setData(meta, CREATOR, id, true);
//            this.setData(meta, UPDATER, id, true);
//        }
    }

    @Override
    public void updateFill(MetaObject meta) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        this.setData(meta, U_TIME, df.format(new Date()), true);
        this.setData(meta, U_TIME1, df.format(new Date()), true);
    }
}
